import React, { useEffect, useState } from 'react'
import { Header } from 'src/components'
import { searchNearby } from 'src/api/getData'
import { useDispatch, useSelector } from 'react-redux'
import { SAVE_ADDDETAIL } from 'src/redux/action-type'
import { useHistory } from 'react-router-dom'
import './index.scss'

const AddAddressDetail = () => {
    const { addAddress } = useSelector(state => state);
    const dispatch = useDispatch();
    const history = useHistory();
    const [warning, setWarnging] = useState(true)
    const [inputAddress, setIputAddress] = useState('')
    const [addressList, setAddressList] = useState([])//地址列表

    useEffect(() => {
        if (addAddress) {
            setIputAddress(addAddress)
        }
    }, [addAddress])

    //搜索地址
    const inputThing = () => {
        searchNearby(inputAddress).then(res => {
            setAddressList(res.data)
            setWarnging(true)
            if (res.data.length > 0) {
                setWarnging(false)
                if (inputAddress === '') {
                    setAddressList([])
                    setWarnging(true)
                }
            }
        });
    }

    //选择地址
    const listClick = (index) => {
        dispatch({
            type: SAVE_ADDDETAIL,
            addAddress: addressList[index].name
        })
        history.go(-1);
    }

    return <div className="page_profile_info_address_add_detail">
        <Header title="搜索地址" goBack></Header>
        <section>
            <div className="add-detail">
                <input type="text" placeholder="请输入小区/写字楼/学校等"
                    value={inputAddress}
                    onInput={(e) => setIputAddress(e.target.value)}
                />
                <button onClick={inputThing}>确认</button>
            </div>
            <div className="warnpart">为了满足商家的送餐要求，建议您从列表中选择地址</div>
            {
                warning && <div className="point">
                    <p>找不到地址？</p>
                    <p>请尝试输入小区、写字楼或学校名</p>
                    <p>详细地址（如门牌号）可稍后输入哦。</p>
                </div>
            }
        </section>
        {
            addressList && <section className="poisearch-container">
                <ul>
                    {
                        addressList.map((item, index) => {
                            return <li key={index} onClick={() => listClick(index)}>
                                <p>{item.name}</p>
                                <p>{item.address}</p>
                            </li>
                        })
                    }
                </ul>
            </section>
        }
    </div>
}


export default AddAddressDetail